package org.openbpm.sys.permission.impl;

import com.alibaba.fastjson.JSONObject;
import org.openbpm.base.core.util.AppUtil;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.base.core.util.ThreadMapUtil;
import org.openbpm.org.api.model.IGroup;
import org.openbpm.org.api.service.GroupService;
import org.openbpm.sys.api.permission.IPermissionCalculator;
import org.openbpm.sys.util.ContextUtil;

import java.util.List;
import java.util.Map;
/**
 * <pre>
 * 描述：组 抽象类
 * </pre>
 */
public abstract class GroupPermissionCalculator implements IPermissionCalculator {
    /**
     * 线程变量ThreadMapUtil中关于当前权限解析器的线程变量
     */
    private static String threadMapKey = "org.openbpm.sys.permission.impl.GroupPermission";

    @Override
    public boolean haveRights(JSONObject json) {
        Map<String, List<? extends IGroup>> allGroup = (Map<String, List<? extends IGroup>>) ThreadMapUtil.get(threadMapKey);
        if(allGroup ==null) {
            GroupService groupService = AppUtil.getBean(GroupService.class);
            allGroup = groupService.getAllGroupByUserId(ContextUtil.getCurrentUserId());
            ThreadMapUtil.put(threadMapKey, allGroup);
        }
        List<? extends IGroup> groups = allGroup.get(this.getType());
        // fix 原来基于雪花主键contains判断是否包含的机制在非等长主健时存在bug，需要拆分group的id分别进行比较
        String[] idArray = json.getString("id").split(",");
        if(groups != null && idArray!=null) {
            for (IGroup group : groups) {
                for(String id: idArray){
                    if(StringUtil.isEmpty(id)){
                        continue;
                    }
                    if(id.equals(group.getGroupId())){
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
